package edu.bluebeanforum.controller;

import edu.bluebeanforum.common.AppResult;
import edu.bluebeanforum.common.ResultCode;
import edu.bluebeanforum.config.AppConfig;
import edu.bluebeanforum.model.User;
import edu.bluebeanforum.service.IUserService;
import edu.bluebeanforum.service.impl.UserServiceImpl;
import edu.bluebeanforum.utils.MD5Util;
import edu.bluebeanforum.utils.StringUtil;
import edu.bluebeanforum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.omg.PortableInterceptor.USER_EXCEPTION;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static edu.bluebeanforum.config.AppConfig.USER_SESSION;

@Api(tags = "用户接口")
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {
    @Resource
    private UserServiceImpl userService;

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
//        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(nickname)
//        || StringUtil.isEmpty(password) || StringUtil.isEmpty(passwordRepeat)) {
//            // 返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }

        // 校验密码与重复密码是否相同
        if (!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            // 返回错误信息
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        // 准备数据
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 处理密码
        // 1. 生成盐
        String salt = UUIDUtil.UUID_32();
        // 2. 生成密码的密文
        String encryptPassword = MD5Util.md5Salt(password, salt);
        // 3. 设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);

        // 调用Service层
        userService.createNormalUser(user);
        // 返回成功
        return AppResult.success();
    }


    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AppResult login(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password,
                           HttpServletRequest request) {
//        1、调用service中login的登录逻辑 返回User对象
        User user = userService.login(username, password);
        if (user == null) {
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.fail(ResultCode.FAILED_LOGIN);
        }
//        2、如果登录成功，则设置到session中
        HttpSession session = request.getSession(true);//没有session也创建
        session.setAttribute(USER_SESSION, user);
//        3、返回结果
        return AppResult.success();
    }

    @GetMapping("/logout")
    @ApiOperation("退出登录")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if (session != null) {
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @GetMapping("/info")
    @ApiOperation("获取用户信息")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户Id") @RequestParam(value = "id", required = false) Long id) {
        User user = null;
//       根据id的有无来判断用户信息的获取
        if (id == null) {
//        1、如果id 为空，则从session中获取用户信息
            HttpSession session = request.getSession(false);//没有session不创建
           /* //判断session对象和用户信息是否有效
            if(session==null||session.getAttribute(USER_SESSION)==null){
                //当用户未登录时，不允许获取，直接返回错误信息
                return AppResult.fail(ResultCode.FAILED_FORBIDDEN);

                 添加拦截器了 不用判断了
            }*/
            user = (User) session.getAttribute(USER_SESSION);
        } else {
//        2、如果id不为空,则根据id从数据库中获取用户信息
            user = userService.selectById(id);
        }
        if (user == null) {
            //返回用户不存在的信息
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "username",required = false)  String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false)  String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false)  String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false)  String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false)  String remark){
        //1、接收参数
        //2、对参数做非空校验
        if(StringUtil.isEmpty(username)&&StringUtil.isEmpty(nickname)
        &&StringUtil.isEmpty(email)&&StringUtil.isEmpty(phoneNum)
        &&StringUtil.isEmpty(remark)&&gender==null){
            //返回错误信息
            return AppResult.fail("请输入要修改的内容");
        }
        //从session中获取用户id
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(USER_SESSION);
        //3、封装对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setEmail(email);
        updateUser.setRemark(remark);

        //4、调用service中的方法
        userService.modifyInfo(updateUser);
        //5、查询最新的用户信息
        user=userService.selectById(user.getId());
        //6、把最新的用户信息设置到session中
        session.setAttribute(USER_SESSION,user);
        //7、返回结果
        return AppResult.success();
    }


    @ApiOperation("修改头像")
    @RequestMapping(value = "/editAvatarUrl",method = RequestMethod.POST)
    public AppResult editAvatarUrl (HttpServletRequest request , @RequestPart("file") MultipartFile file) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        userService.editAvatarUrl(user,file);
        return AppResult.success();
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        if (!newPassword.equalsIgnoreCase(passwordRepeat)){
            return AppResult.fail(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(USER_SESSION);
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁session
        if(session!=null){
            session.invalidate();
        }
        return AppResult.success();

    }
}
